package com.shinetech.service;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.shinetech.controller.BaseController;
import com.shinetech.entity.Menu;
import com.shinetech.entity.User;
import com.shinetech.repository.MenuRepository;
import com.shinetech.repository.UserRepository;
import com.shinetech.utils.TreeUtils;
import com.shinetech.vo.MenuTree;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by joy on 2017/7/1.
 */
@Service
public class UserService  extends BaseService<User>{

    @Resource
    private MenuRepository menuRepository;

    public String getSystemsByUsername(String currentUserName) {
        long userId = ((UserRepository)repository).getUserByUsername(currentUserName).getId();
        return JSONObject.toJSONString(menuRepository.getMenusByUserId(userId));
    }

    public String getMenusByUsername(String currentUserName, Long parentId) {
        long userId = ((UserRepository)repository).getUserByUsername(currentUserName).getId();
        try {
            if (parentId == null||parentId<0) {
                parentId = menuRepository.getMenusByUserId(userId).get(0).getId();
            }
        } catch (Exception e) {
            return JSONObject.toJSONString(new ArrayList<MenuTree>());
        }
        return JSONObject.toJSONString(getMenuTree(menuRepository.getMenusByUserId(userId), parentId));

    }

    private List<MenuTree> getMenuTree(List<Menu> menus, long root) {
        List<MenuTree> trees = new ArrayList<MenuTree>();
        MenuTree node = null;
        for (Menu menu : menus) {
            node = new MenuTree();
            BeanUtils.copyProperties(menu, node);
            trees.add(node);
        }
        return TreeUtils.build(trees, root) ;
    }


    public List<User> selectByName(int pagesize,int page,String name){
        Pageable pageable = new PageRequest(page,pagesize, Sort.Direction.DESC,"id");
        List<User> list = new ArrayList<>();
        Page<User> pages = null;
        if(Strings.isNullOrEmpty(name)){
            pages = repository.findAll(pageable);
        }else{
            User user = new User();
            user.setName(name);
            user.setUsername(name);
            Example example = Example.of(user,ExampleMatcher.matching()
                    .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                    .withIgnoreCase(true));
            pages = repository.findAll(example,pageable);
        }
        if(pages != null ){
            list = pages.getContent();
        }
        return list;
    }

}
